<!-- src/views/student/MaterialSubmission.vue -->
<template>
  <div class="material-submission">
    <div class="header">
      <el-page-header @back="goBack">
        <template #content>
          <span class="title">实习材料提交</span>
        </template>
      </el-page-header>
      <div class="actions">
        <el-button type="primary" @click="showSubmitDialog">提交新材料</el-button>
      </div>
    </div>

    <!-- 材料列表 -->
    <el-table
      :data="materials"
      v-loading="loading"
      style="width: 100%"
      class="material-table"
    >
      <el-table-column prop="title" label="材料名称" min-width="180" />
      <el-table-column prop="internshipId" label="实习ID" min-width="100" />
      <el-table-column prop="typeName" label="材料类型" min-width="120" />
      <el-table-column prop="submittedAt" label="提交时间" min-width="180">
        <template #default="scope">
          {{ formatDate(scope.row.submittedAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="120">
        <template #default="scope">
          <el-tag :type="getMaterialStatusType(scope.row.status)">
            {{ getMaterialStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            @click="viewMaterialDetail(scope.row)"
          >
            查看详情
          </el-button>
          <el-button
            size="small"
            type="primary"
            @click="editMaterial(scope.row)"
            :disabled="scope.row.status !== 0"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="deleteMaterial(scope.row)"
            :disabled="scope.row.status !== 0"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 提交/编辑材料对话框 -->
    <el-dialog
      v-model="submitDialogVisible"
      :title="isEditing ? '编辑材料' : '提交新实习材料'"
      width="600px"
    >
      <el-form
        :model="materialForm"
        :rules="materialRules"
        ref="materialFormRef"
        label-width="100px"
      >
        <el-form-item label="选择实习" prop="selectedInternship">
          <el-select
            v-model="materialForm.selectedInternship"
            placeholder="请选择实习"
            style="width: 100%"
            @change="onInternshipChange"
            :disabled="isEditing"
          >
            <el-option
              v-for="internship in internships"
              :key="internship.internshipId"
              :label="`${internship.companyName} - ${internship.positionTitle}`"
              :value="internship"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="材料标题" prop="title">
          <el-input v-model="materialForm.title" placeholder="请输入材料标题" />
        </el-form-item>

        <el-form-item label="材料类型" prop="type">
          <el-select v-model="materialForm.type" placeholder="请选择材料类型" style="width: 100%" @change="onMaterialTypeChange">
            <el-option label="周志" :value="1" />
            <el-option label="实习报告" :value="2" />
            <el-option label="最终成果" :value="3" />
            <el-option label="其他" :value="4" />
          </el-select>
        </el-form-item>

        <el-form-item
          label="材料内容"
          prop="content"
          v-if="materialForm.type !== 2"
        >
          <el-input
            v-model="materialForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入材料内容"
          />
        </el-form-item>

        <el-form-item
          label="文件链接"
          prop="fileUrl"
        >
          <el-input
            v-model="materialForm.fileUrl"
            placeholder="请输入文件链接"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submitDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitMaterialForm"
            :loading="submitLoading"
          >
            {{ isEditing ? '更新' : '提交' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 材料详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="材料详情"
      width="700px"
    >
      <div v-if="selectedMaterial" class="material-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="材料标题">{{ selectedMaterial.title }}</el-descriptions-item>
          <el-descriptions-item label="实习ID">{{ selectedMaterial.internshipId }}</el-descriptions-item>
          <el-descriptions-item label="材料类型">{{ getMaterialTypeLabel(selectedMaterial.type) }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ formatDate(selectedMaterial.submittedAt) }}</el-descriptions-item>
          <el-descriptions-item label="材料状态">
            <el-tag :type="getMaterialStatusType(selectedMaterial.status)">
              {{ getMaterialStatusLabel(selectedMaterial.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核时间" v-if="selectedMaterial.reviewedAt">
            {{ formatDate(selectedMaterial.reviewedAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="拒绝原因" v-if="selectedMaterial.rejectReason">
            {{ selectedMaterial.rejectReason }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="content-section" v-if="selectedMaterial.content">
          <h3>材料内容</h3>
          <div class="material-content">{{ selectedMaterial.content }}</div>
        </div>

        <div class="file-section" v-if="selectedMaterial.fileUrl">
          <h3>附件</h3>
          <el-link :href="selectedMaterial.fileUrl" target="_blank">下载附件</el-link>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { useStudentStore } from '../../store/student'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const studentStore = useStudentStore()
const router = useRouter()

const materials = ref([])
const internships = ref([])  // 存储学生实习信息
const loading = ref(false)
const submitLoading = ref(false)
const submitDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const selectedMaterial = ref(null)
const materialFormRef = ref()
const isEditing = ref(false)
const editingMaterialId = ref(null)
const studentId = ref(null)  // 存储当前学生ID

// 材料表单
const materialForm = reactive({
  selectedInternship: null,  // 选择的实习对象
  internshipId: null,        // 实习ID（从选择的实习中获取）
  title: '',
  type: 1,
  content: '',
  fileUrl: ''
})

// 表单规则
const materialRules = {
  selectedInternship: [
    { required: true, message: '请选择实习', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入材料标题', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择材料类型', trigger: 'change' }
  ]
}

// 获取材料列表
const fetchMaterials = async () => {
  loading.value = true
  try {
    const response = await studentStore.fetchMaterials()
    // 为每个材料添加类型名称
    const materialsWithTypeName = (response.content || response).map(material => {
      return {
        ...material,
        typeName: getMaterialTypeLabel(material.type)
      }
    })
    materials.value = materialsWithTypeName
  } catch (error) {
    ElMessage.error('获取材料列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 获取学生实习信息
const fetchStudentInternships = async () => {
  try {
    if (!studentId.value) {
      ElMessage.error('无法获取学生信息')
      return
    }

    // 使用新接口获取学生实习信息
    const response = await studentStore.fetchStudentInternships(studentId.value)
    internships.value = response || []
  } catch (error) {
    ElMessage.error('获取实习信息失败: ' + (error.response?.data?.message || error.message))
  }
}

// 获取学生ID
const fetchStudentId = async () => {
  try {
    // 通过获取申请记录来获取学生ID
    const response = await studentStore.fetchApplications()
    const applications = response.content || response

    // 从任意一个申请记录中获取学生ID
    if (applications && applications.length > 0) {
      studentId.value = applications[0].studentId
    }
  } catch (error) {
    console.error('获取学生ID失败:', error)
  }
}

// 显示提交对话框
const showSubmitDialog = async () => {
  isEditing.value = false
  editingMaterialId.value = null

  // 重置表单
  Object.keys(materialForm).forEach(key => {
    materialForm[key] = key === 'type' ? 1 : (key === 'selectedInternship' ? null : '')
  })

  // 获取学生ID
  if (!studentId.value) {
    await fetchStudentId()
  }

  // 获取学生的实习信息
  await fetchStudentInternships()

  submitDialogVisible.value = true

  // 等待DOM更新后清除验证
  nextTick(() => {
    if (materialFormRef.value) {
      materialFormRef.value.clearValidate()
    }
  })
}

// 编辑材料
const editMaterial = async (material) => {
  isEditing.value = true
  editingMaterialId.value = material.id

  // 获取学生ID
  if (!studentId.value) {
    await fetchStudentId()
  }

  // 获取学生的实习信息
  await fetchStudentInternships()

  // 查找对应的实习对象
  const selectedInternship = internships.value.find(internship => internship.internshipId === material.internshipId)

  // 填充表单数据
  materialForm.selectedInternship = selectedInternship || null
  materialForm.internshipId = material.internshipId
  materialForm.title = material.title
  materialForm.type = material.type
  materialForm.content = material.content || ''
  materialForm.fileUrl = material.fileUrl || ''
  submitDialogVisible.value = true
}

// 删除材料
const deleteMaterial = (material) => {
  // 只有待审核状态的材料才能删除
  if (material.status !== 0) {
    ElMessage.warning('只有待审核的材料才能删除')
    return
  }

  ElMessageBox.confirm(
    `确定要删除材料"${material.title}"吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await studentStore.deleteMaterial(material.id)
      ElMessage.success('删除成功')
      await fetchMaterials() // 重新加载列表
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 实习选择变化时的处理
const onInternshipChange = (internship) => {
  materialForm.internshipId = internship ? internship.internshipId : null
}

// 材料类型改变时的处理
const onMaterialTypeChange = () => {
  // 清除验证状态
  nextTick(() => {
    if (materialFormRef.value) {
      materialFormRef.value.clearValidate(['content'])
    }
  })
}

// 提交材料表单
const submitMaterialForm = async () => {
  if (!materialFormRef.value) return

  await materialFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 验证实习ID是否存在
        if (!materialForm.internshipId) {
          ElMessage.error('请选择有效的实习')
          submitLoading.value = false
          return
        }

        // 准备提交数据
        const data = {
          internshipId: materialForm.internshipId,
          title: materialForm.title,
          type: materialForm.type
        }

        // 根据类型决定是否包含content字段
        if (materialForm.type !== 2 && materialForm.content) {
          data.content = materialForm.content
        }

        // 始终包含fileUrl字段
        data.fileUrl = materialForm.fileUrl || ''

        if (isEditing.value) {
          // 编辑材料
          await studentStore.updateMaterial(editingMaterialId.value, data)
          ElMessage.success('材料更新成功')
        } else {
          // 提交新材料
          await studentStore.submitMaterial(data)
          ElMessage.success('材料提交成功')
        }

        submitDialogVisible.value = false
        fetchMaterials() // 重新加载列表
      } catch (error) {
        console.error('提交材料错误:', error)
        ElMessage.error((isEditing.value ? '更新' : '提交') + '失败: ' + (error.response?.data?.message || error.message))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 查看材料详情
const viewMaterialDetail = async (material) => {
  try {
    const response = await studentStore.getMaterialDetail(material.id)
    selectedMaterial.value = response
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取材料详情失败: ' + (error.response?.data?.message || error.message))
  }
}

// 获取材料类型标签
const getMaterialTypeLabel = (type) => {
  switch (type) {
    case 1: return '周志'
    case 2: return '实习报告'
    case 3: return '最终成果'
    case 4: return '其他'
    default: return '未知'
  }
}

// 获取材料状态标签类型
const getMaterialStatusType = (status) => {
  switch (status) {
    case 0: return 'info'     // 待审核
    case 1: return 'success'  // 已通过
    case 2: return 'danger'   // 已拒绝
    default: return ''
  }
}

// 获取材料状态标签文本
const getMaterialStatusLabel = (status) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '已通过'
    case 2: return '已拒绝'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString()
}

// 返回上一级
const goBack = () => {
  router.go(-1)
}

onMounted(() => {
  fetchMaterials()
})
</script>

<style scoped>
.material-submission {
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.material-table {
  margin-bottom: 20px;
}

.material-detail h3 {
  margin: 15px 0 10px 0;
}

.content-section {
  margin-top: 15px;
}

.material-content {
  white-space: pre-wrap;
  line-height: 1.6;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
